/**
 * Copyright (C) 2013 SHANGHAI VOLKSWAGEN, All rights reserved.
 * License version 1.0, a copy of which has been included with this.
 *
 * @File name：com.bwie.community.service.impl.CommunityServiceImpl
 * @Create on：2024/3/24
 * @Author：liuchang
 */
package com.bwie.community.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.domain.VoObserve;
import com.bwie.common.domain.*;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.request.CommunityReq;
import com.bwie.common.result.PageResult;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.MsgUtil;
import com.bwie.community.config.MqConfig;
import com.bwie.community.mapper.CommunityMapper;
import com.bwie.community.service.CommunityService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>ClassName：CommunityServiceImpl</p >
 * <p>Description：</p >
 * <p>Author：liuchang</p >
 * <p>Date：2024/3/24</p >
 */
@Service
public class CommunityServiceImpl implements CommunityService {
    @Autowired
    private CommunityMapper communityMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    /*
    *
    * 发布朋友圈
    * */
    @Override
    public Result publish(Community community) {
        User user=getInfo();
        community.setUserId(user.getUserId());
        Date date = new Date();

        community.setCreateTime(date);
         //添加病友圈表
        Integer i=communityMapper.publish(community);
        if (i>0){
            String[] split = community.getExperience().split(",");
            //添加图片表
            communityMapper.addImage(community.getId(),split);

        }
        return Result.success(i,"发布成功");
    }

    @Override
    public List<Dept> findAllDept() {
        return communityMapper.findAllDept();
    }
    /**
     * <p>朋友圈列表搜索</p >
     * @author：liuchang
     * @date：
     * @param：
     * @return：
    */
    @Override
    public Result<PageResult<DTOCommunity>> search(CommunityReq req) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<DTOCommunity> list=communityMapper.search(req);
        PageInfo<DTOCommunity> info = new PageInfo<>(list);
        return PageResult.toResult(info.getTotal(),list);
    }



    /**
     * <p>根据observeId查找用户信息</p >
     * @author：liuchang
     * @date：
     * @param：
     * @return：
    */
    @Override
    public DTOObserve findUserInfoByObserveId(Integer observeId) {

        return communityMapper.findUserInfoByObserveId(observeId);
    }

    /**
     * <p>递归查找所有子评论</p >
     * @author：liuchang
     * @date：
     * @param：
     * @return：
    */
    @Override
    public Result<List<DTOObserve>> findObserveListByCid(Integer cid) {
        List<DTOObserve> list=communityMapper.findObserveListByCid(cid);

        List<DTOObserve> collect = list.stream().filter(
                dtoObserve -> {
                    return dtoObserve.getLastId() == 0;
                }
        ).map(
                dtoObserve -> {
                    dtoObserve.setChildren(getChildren(list, dtoObserve).isEmpty() ? null : getChildren(list, dtoObserve));
                    return dtoObserve;
                }
        ).sorted(
                new Comparator<DTOObserve>() {
                    @Override
                    public int compare(DTOObserve o1, DTOObserve o2) {
                        return (int) (o1.getCreateTime().getTime()-o2.getCreateTime().getTime());
                    }
                }
        ).collect(Collectors.toList());


        return Result.success(collect);
    }

    @Override
    public Result addComment(VoObserve voObserve) {
        Integer userId = getInfo().getUserId();
        voObserve.setObserveId(userId);

        //String转Date
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        try {
            Date date = simpleDateFormat.parse(format);
            voObserve.setCreateTime(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        Integer i=communityMapper.addComment(voObserve);
        rabbitTemplate.convertAndSend(MqConfig.MESSAGE_EXCHANGE,MqConfig.MESSAGE_ROUTE_KEY,
                voObserve.getObserveId(),message -> {
            message.getMessageProperties().setMessageId(UUID.randomUUID().toString().replaceAll("-","")+new Date().getTime());
            return message;
                },new CorrelationData(UUID.randomUUID().toString().replaceAll("-","")+new Date().getTime()));
        return Result.success(i,"评论成功");
    }
    /**
     * <p>查找自己的朋友圈</p >
     * @author：liuchang
     * @date：2024/4/5 19:40
     * @param：* @param voCommunityReq
     * @return：
     * @return Result<PageResult<Community>>
    **/
    @Override
    public Result<PageResult<Community>> findCommunityByUserId(VoCommunityReq voCommunityReq) {
        PageHelper.startPage(voCommunityReq.getPageNum(),voCommunityReq.getPageSize());

        List<Community> list=communityMapper.findCommunityByUserId(voCommunityReq.getUserId());

        PageInfo<Community> communityPageInfo = new PageInfo<>(list);

        return PageResult.toResult(communityPageInfo.getTotal(),list);
    }

    /**
     * <p>生成PDF</p >
     * @author：liuchang
     * @date：2024/4/6 20:06
     * @param：
     * @param receive receive
     * @param response response
     * @return：
    */

    @Override
    public void generatePDF( HttpServletResponse response) throws Exception {

//        String templateName="test.pdf";
//        String path="D:\\pdf\\";
//        String fileName=receive.getDiseaseDescription()+"诊断报告.pdf";
//        fileName = URLEncoder.encode(fileName, "UTF-8");
//        response.setContentType("application/force-download");
//        response.setHeader("Content-Disposition",
//                "attachment;fileName=" + fileName);
//        OutputStream out=null;
//        ByteArrayOutputStream bos=null;
//        PdfStamper stamper=null;
//        PdfReader reader=null;
//
//        try {
//            out=new FileOutputStream(fileName);
//            reader=new PdfReader(path+templateName);
//            bos=new ByteArrayOutputStream();
//            stamper=new PdfStamper(reader,bos);
//            AcroFields form = stamper.getAcroFields();
//            // 给表单生成中文字体，这里采用系统字体，不设置的话，中文显示会有问题
//            BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//           form.addSubstitutionFont(font);
//           //装配数据
//            HashMap<String, Object> data = new HashMap<>();
//            data.put("diseaseDescription",receive.getDiseaseDescription());
//            data.put("receiveInformation",receive.getReceiveInformation());
//
//            for (String key : data.keySet()) {
//                form.setField(key,data.get(key).toString());
//            }
//
//            stamper.setFormFlattening(true);
//
//            stamper.close();

        Document document = new Document();
        PdfWriter.getInstance(document,new FileOutputStream("D:\\pdf\\test02.pdf"));
        document.open();
        document.add(new Paragraph("change"));
        document.close();
        System.out.println("-----pdf生成成功----");

    }


    /**
     * <p>获取子集集合</p >
     * @author：liuchang
     * @date：2024/4/5 19:40
     * @param：* @param list
     * @param dtoObserve
     * @return：
     * @return List<DTOObserve>
    **/
    private List<DTOObserve> getChildren(List<DTOObserve> list,DTOObserve dtoObserve){
        List<DTOObserve> collect = list.stream().filter(dtoObserve1 -> {
            return Objects.equals(dtoObserve.getId(),dtoObserve1.getLastId());
        }).map(
                dtoObserve1 -> {
                    dtoObserve1.setChildren(getChildren(list,dtoObserve1).isEmpty()?null:getChildren(list,dtoObserve1));
                    return dtoObserve1;
                }
        ).sorted(new Comparator<DTOObserve>() {
            @Override
            public int compare(DTOObserve o1, DTOObserve o2) {
                return (int) (o1.getCreateTime().getTime() - o2.getCreateTime().getTime());
            }
        }).collect(Collectors.toList());

        return collect;
    }


    /**
     * <p></p >
     * @author：liuchang
     * @date：2024/4/5 19:39
     * @param：* @param
     * @return：
     * @return User
    **/
    private User getInfo(){
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String s = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        User user = JSONObject.parseObject(s, User.class);
        return user;

    }
}
